package com.hh.shiro.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hh.shiro.web.PathUtil;
import com.hh.shiro.web.WebConstant;
import com.hh.shiro.web.vo.LoginRequestVo;

@Controller
@RequestMapping("/auth")
public class LogonLogoutPageController {

	private static Logger LOGGER = LoggerFactory.getLogger(LogonLogoutPageController.class);
	
	/** 去登录页面 */
	@RequestMapping(value = "/loginPage")
	public ModelAndView gotoLogin(HttpSession session) {
		ModelAndView mv = new ModelAndView("auth/login");
		String errorMsg = (String) session.getAttribute(WebConstant.SESSOIN_AUTH_ERROR_MSG);
		if (StringUtils.isNotBlank(errorMsg)) {
			session.removeAttribute(WebConstant.SESSOIN_AUTH_ERROR_MSG);
			mv.addObject("errorMsg", errorMsg);
		}
		return mv;
	}

	/** 登录请求 */
	@RequestMapping(value = "/login")
	public String loginOn(LoginRequestVo vo, HttpSession session, HttpServletRequest request) {
		String username = vo.getUsername();
		String password = vo.getPassword();
		Boolean rememberme = vo.getRemember();
		String view = StringUtils.EMPTY;
		String errorMsg = StringUtils.EMPTY;
		if (null == vo || StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			errorMsg = "用户或密码不能为空";
			view = "redirect:/auth/loginPage";
		} else {
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			if (BooleanUtils.isTrue(rememberme)) {
				token.setRememberMe(true);
			}
			Subject subject = SecurityUtils.getSubject();
			try {
				subject.login(token);
				view = "redirect:" + PathUtil.getWholePath(request, "/auth/login", "/main/index");
			} catch (UnknownAccountException e) {
				errorMsg = "用户不存在";
				LOGGER.error(errorMsg);
				view = "redirect:/auth/loginPage";
			} catch (IncorrectCredentialsException e) {
				errorMsg = "用户密码不正确";
				LOGGER.error(errorMsg);
				view = "redirect:/auth/loginPage";
			}
		}
		session.setAttribute(WebConstant.SESSOIN_AUTH_ERROR_MSG, errorMsg);
		return view;
	}

	
	/** 注销请求,然后跳到登录页面 */
	@RequestMapping(value = "/loginOut")
	public String getLoginOutPage(ModelMap model) {
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return "redirect:/auth/loginPage";
	}

	@RequestMapping(value = "/registe")
	public ModelAndView gotoRegister() {
		ModelAndView mv = new ModelAndView("auth/registe");
		return mv;
	}
	
}
